var rootPath = '';//kk.getRootPath();

/* CRUD 1: Create, 2: Read, 3: Update, 4: Delete */
var CREATE = 1, READ = 2, UPDATE = 3, DELETE = 4;
function CRUDCodeFunc(operCode, id, index, bookId) {
//	console.log(bookId);
	/* codeDom */
	var codeDom = '\
	<form class="form-horizontal" id="codeForm">\
		<div>\
			<input type="hidden" name="id" />\
			<input type="hidden" name="tid" value="' + bookId + '">\
			<input type="hidden" id="startDatetime" name="start_datetime" />\
			<input type="hidden" id="endDatetime" name="end_datetime" />\
		</div>\
		<div class="form-group">\
			<label for="name" class="col-sm-2 control-label">名称<span class="text-red">*</span></label>\
			<div class="col-sm-10">\
				<input type="text" class="form-control" id="name" name="name" placeholder="名称">\
			</div>\
		</div>\
		<div class="form-group">\
			<label for="type" class="col-sm-2 control-label">类型</label>\
			<div class="col-sm-10">\
				<div id="type">\
					<input type="radio" name="type" value="1" data-label="小班" checked />\
					<input type="radio" name="type" value="2" data-label="中班" />\
					<input type="radio" name="type" value="3" data-label="大班" />\
					<input type="radio" name="type" value="4" data-label="小学" />\
				</div>\
			</div>\
		</div>\
		<div class="form-group">\
			<label for="price" class="col-sm-2 control-label">价格<span class="text-red">*</span></label>\
			<div class="col-sm-10">\
				<div class="input-group">\
					<input type="number" class="form-control" id="price" name="price" placeholder="价格" value="0" min="0" />\
					<span class="input-group-addon">¥</span>\
				</div>\
			</div>\
		</div>\
		<div class="form-group">\
			<label for="datetimeRange" class="col-sm-2 control-label">起止时间</label>\
			<div class="col-sm-10">\
				<div class="input-group">\
					<input type="text" class="form-control" id="datetimeRange" placeholder="起止时间" />\
					<div class="input-group-addon"><i class="fa fa-calendar"></i></div>\
				</div>\
			</div>\
		</div>\
		<div class="form-group">\
			<label for="maxNumber" class="col-sm-2 control-label">最大人数</label>\
			<div class="col-sm-10">\
				<input type="number" class="form-control" id="maxNumber" name="max_count" placeholder="最大人数" value="0" min="0" />\
			</div>\
		</div>\
	</form>\
	';
	
	var canOpen = false;
	var url;
	var obj;
	
	if (operCode == CREATE) {
		canOpen = true;
	} else if (operCode == READ || operCode == UPDATE) {
    	url = rootPath + '/Book/Code/find?id=' + id;
		obj = kk.getObj(url);
		if (obj != null) {
			canOpen = true;
		}
	} else if (operCode == DELETE) {
    	url = rootPath + '/Book/Code/delete?id=' + id;
		kk.deleteObj(url, '#codeTable');
	} else {
		return false;
	}
	
	if (!canOpen) {
		return false;
	}
	
	var validator;
	
	xpopup.window({
	    width: 800,
		title: '编辑',		// 因为afterShow中已经有新建和查看了
	    content: codeDom,
        buttons: [{
        	id:	'btnOk',
            text: '确定',
            'class': 'btn btn-info btn-flat',
            handler: function ($this) {
    	 		if (validator.form() && doCUCode(operCode, id, index)) {
            		$this.destroy();
    	 		}
            }
        }, {
        	id:	'btnCancel',
            text: '取消',
            'class': 'btn btn-default btn-flat',
            handler: function ($this) {
        		$this.destroy();
            }
        }],
        afterShow: function ($this) {
			if (operCode == CREATE) {
				$this.setTitle('添加');
	        	$('#startDatetime').val(kk.timeFormat('yyyy-MM-dd HH') + ':00');
	        	$('#endDatetime').val(kk.timeFormat('yyyy-MM-dd HH') + ':00');
	        	$('#datetimeRange').daterangepicker({
		        //	"autoApply": true,						// NO USE???+++
	        		"timePicker": true,
	        		"timePickerIncrement": 30,
	        		"timePicker24Hour": true,
	        		"locale": {
	        			format: 'YYYY-MM-DD hh:mm',
	        		},
	        	    "startDate": $('#startDatetime').val(),
	        	    "endDate": $('#endDatetime').val()
	        	}, function(start, end, label) {
	        		  console.log('New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')');
	        		  $('#startDatetime').val(start.format('YYYY-MM-DD hh:mm'));
	        		  $('#endDatetime').val(end.format('YYYY-MM-DD hh:mm'));
	        	});
				
				$('.rm-or-hide').remove();
			} else if (operCode == READ) {
				$this.setTitle('查看');
				$('#btnOk').hide();
	    		$('#btnCancel').text('关闭');

				$('#codeForm').setForm(obj);
				$('#datetimeRange').val(obj.start_datetime + ' - ' + obj.end_datetime);

				$('#codeForm').find(':input').attr("disabled", "disabled");		// 习惯性地处理
			} else if (operCode == UPDATE) {					
				$this.setTitle('编辑');

				$('#codeForm').setForm(obj);
				$('#startDatetime').val(kk.timeFormat('yyyy-MM-dd HH:mm', obj.start_datetime));
				$('#endDatetime').val(kk.timeFormat('yyyy-MM-dd HH:mm', obj.end_datetime));
	        	$('#datetimeRange').daterangepicker({
	        	//	"autoApply": true,						// NO USE???+++
	        		"timePicker": true,
	        		"timePickerIncrement": 30,
	        		"timePicker24Hour": true,
	        		"locale": {
	        			format: 'YYYY-MM-DD hh:mm',
	        		},
	        	    "startDate": $('#startDatetime').val(),
	        	    "endDate": $('#endDatetime').val()
	        	}, function(start, end, label) {
	        		  console.log('New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')');
	        		  $('#startDatetime').val(start.format('YYYY-MM-DD hh:mm'));
	        		  $('#endDatetime').val(end.format('YYYY-MM-DD hh:mm'));
	        	});

				$('.rm-or-hide').hide();
			}
			
    		xrs("input:radio[name='type']", {
    			xRsLabelClass: 'xrs-label-info',
    		});

        	validator = $("#codeForm").validate({
    			onfocusout: function(element) {
    				$(element).valid();
    			},
                rules: {
        			name: "required",
                },
                messages: {
                	name: "请输入名称",
                }
            });
        }
	});
}

/* Create & Update */
function doCUCode(operCode, id, index) {
    var url;
    var method;
	var jsonStr = JSON.stringify($('#codeForm').serializeObject());
	var result;
	
	if (operCode == CREATE) {
		url = rootPath + '/Book/Code/save';
		method = "POST";

		result = kk.doStrAjax(url, method, jsonStr);
	    if (result.code == 0) {
	    	$('#codeTable').bootstrapTable('insertRow', {
				index: 0,
				row: result.obj
			});

        	return true;
		}
	} else if (operCode == UPDATE) {
		url = rootPath + '/Book/Code/update?id='+ id;
		method = "PUT";

		result = kk.doStrAjax(url, method, jsonStr);
	    if (result.code == 0) {
	    	$('#codeTable').bootstrapTable('updateRow', {
	    		index: index,
				row: result.obj
	    	});

        	return true;
		}
	}
	
	return false;
}